<?php

namespace Xin\VerifyCode\Laravel;

use Illuminate\Database\Eloquent\Model;
use Xin\Capsule\Service;
use Xin\VerifyCode\Contracts\Store;

class ModelStoreProvider extends Service implements Store
{

	/**
	 * @inerhitDoc
	 */
	public function save($type, $identifier, $code, $seconds)
	{
		return $this->newModel()->forceFill([
			'type'        => $type,
			'identifier'  => $identifier,
			'code'        => $code,
			'expire_time' => now()->addSeconds($seconds)->getTimestamp(),
		])->save();
	}

	/**
	 * @inerhitDoc
	 */
	public function get($type, $identifier)
	{
		$info = $this->newQuery()
			->where('type', $type)
			->where('identifier', $identifier)
			->where('expire_time', '>', now()->getTimestamp())
			->orderByDesc('id')
			->first();

		if ($info && $info['status'] == 0) {
			return $info['code'];
		}

		return null;
	}

	/**
	 * @inerhitDoc
	 */
	public function forget($type, $identifier)
	{
		$this->newQuery()
			->where('type', $type)
			->where('identifier', $identifier)
			->update([
				'status' => 1,
			]);
	}

	/**
	 * @return Model
	 */
	protected function newModel()
	{
		$modelClass = $this->getConfig('model');

		return new $modelClass;
	}


	/**
	 * @return \Illuminate\Database\Eloquent\Builder
	 */
	protected function newQuery()
	{
		$model = $this->newModel();
		if (method_exists($model, 'newQuery')) {
			return $model->newQuery();
		} elseif (method_exists($model, 'query')) {
			return $model->query();
		}

		return value($model);
	}
}
